{% extends "layouts/webtorrent.html" %}

{% block body %}

<div id="content">
</div>

<script type="text/javascript">
    const client = new window.WebTorrent()
    const cdiv = document.getElementById('content')

    const torrent = client.add('{{ webTorrentId }}')

    function download_file(fileidx) {
      /*
       * Transfer a file from the torrent to IPFS and change the window's
       * location to point to the injected file.
       */

      var elem = document.getElementById(`file${fileidx}`)
      var file = torrent.files[fileidx]

      function prog(bytes, fp) {
          elem.innerHTML = `Downloaded ${ bytes } / ${ file.length } bytes `
      }

      file.getBuffer(function (e, buffer) {
        let result = window.ipfs.add(buffer, { cidVersion: 1, progress: prog }).then(function(res, err) {
          if (err) {
            alert(err)
          } else {
            window.location = `ipfs://${ res[0].hash }`
          }
        })
      })
    }

    torrent.on('ready', () => {
      console.log('Torrent name:', torrent.name)

      for (var idx = 0; idx < torrent.files.length; idx++) {
        var file = torrent.files[idx]
        var path = file.path

        if (path === 'index.html') {
          index = torrent.files[idx]
        }

        let elem = document.createElement('p')
        elem.setAttribute('id', `file${idx}`)
        elem.innerHTML = `
 <a href="#" onclick="event.preventDefault(); download_file(${ idx });">${ file.name }</a>
        `

        file.appendTo(cdiv, { muted: false, autoplay: false })
        cdiv.appendChild(elem)
      }
    })

    torrent.on('error', (err) => {
      alert(err)
    })
</script>

{% endblock %}
